import datetime
import json

import requests
import tushare as ts


class RawRequestAPI:
    """
    最简单原始的API

    """
    pass

    @staticmethod
    def get_buy_sell_1(wap_eastmoney_code):
        """
        使用普通接口获取买一卖一

        secid 后的参数为
        H股为116.0 + 4位股票代号
        A股和债券为1.+ 6位A股代号
        基金为0. + 基金代号

        :param wap_eastmoney_code:
        :param raw_code:
        :return:

        """
        url = "https://push2his.eastmoney.com/api/qt/stock/trends2/get?secid={}&fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14&fields2=f51,f53,f54,f55,f56,f57,f58&iscr=0" \
            .format(wap_eastmoney_code)
        try:
            response = requests.get(url, timeout=2)
            data = json.loads(response.text)["data"]
            if data:
                trend = data['trends'][-1].split(',')
                return trend[0], trend[3], trend[2]
            else:
                return -1, -1, -1
        except:
            return datetime.datetime.now().strftime('%Y-%m-%d %H:%M'), -2, -2


class TuShareAPI():
    """

    TuShare的接口

    """

    @staticmethod
    def get_some_buy1_sell1(codes: list):
        """
        获取买一卖一

        :param codes:
        :return:
        """
        re = ts.get_realtime_quotes(codes)
        sell1s = re.loc[:, 'ask'].values
        buy1s = re.loc[:, 'bid'].values
        time = re.loc[0, 'time']
        return time, list(buy1s), list(sell1s)

    @staticmethod
    def get_one_buy1_sell1_turnover(code: str):
        """
        获取单个买一卖一以及成交量

        :param code:
        :return: 时间，买一，卖一，成交量
        """
        re = ts.get_realtime_quotes([code])
        sell1 = re.loc[0, 'ask']
        buy1 = re.loc[0, 'bid']
        time = re.loc[0, 'time']
        turnover = re.loc[0, 'volume']
        return time, buy1, sell1, turnover
